<template>
	<view class="container">
		<view class="title">
			<view class="text">为了安全 请绑定手机</view>
		</view>
		<!-- 账号密码输入框 -->
		<view class="form login">
			<view class="username">
				<image class="img" src="/static/img/public/account.png" mode="widthFix"></image>
				<input placeholder="请输入手机号" v-model="phoneNumber" maxlength="11" type="number" placeholder-style="color: rgba(172,173,174,0.8);" />
			</view>
			<view class="code">
				<image class="code_img" src="/static/img/public/verificationCode.png" mode="widthFix"></image>
				<view class="get-code" :style="{'color':getCodeBtnColor}" @click.stop="getCode()">{{getCodeText}}</view>
				<input placeholder="请输入验证码" v-model="code" :focus="codeFocus" placeholder-style="color: rgba(172,173,174,0.8);" />
			</view>
			<view class="btn" @tap="bind_mobile">绑定手机</view>
		</view>
	</view>
</template>
<script>
	import {
		mapMutations
	} from 'vuex';
	import Api from '@/common/api';
	import md5 from "@/common/SDK/md5.min.js";
	import JSEncrypt from "@/common/SDK/jsencrypt";
	export default {
		data() {
			return {
				phoneNumber: '',
				code: '',
				passwd: '',
				sid: '',
				timestamp: "",
				publicKey: "",
				privateKey: "",
				getCodeText: '验证码',
				codeFocus: false, //验证码输入框是否聚焦
				getCodeBtnColor: "#767777",
				logining: false,
			}
		},
		onShow() {

		},
		onLoad(option) {
		},
		methods: {
			...mapMutations(['login']),
			async getCode() {
				uni.hideKeyboard()
				if (this.getCodeisWaiting) {
					return;
				}
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) {
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				this.getCodeText = "发送中..."
				this.codeFocus = true;
				this.getCodeisWaiting = true;
				var mobile = {
					'mobile': this.phoneNumber
				};
				let data = await Api.apiCall('post', Api.index.sendCodes, mobile);
				if (data) {
					//示例用定时器模拟请求效果
					setTimeout(() => {
						uni.showToast({
							title: '验证码已发送',
							icon: "success"
						});
						this.setTimer();
					}, 500)
				} else {
					this.getCodeisWaiting = false;
					this.getCodeText = "验证码";

					uni.showToast({
						title: data.error,
						icon: 'none'
					});

				}

			},
			setTimer() {
				let holdTime = 60;
				this.getCodeText = "60秒"
				this.Timer = setInterval(() => {
					if (holdTime <= 0) {
						this.getCodeisWaiting = false;
						this.getCodeBtnColor = "#767777";
						this.getCodeText = "验证码"
						clearInterval(this.Timer);
						return;
					}
					this.getCodeText = holdTime + "秒"
					holdTime--;
				}, 1000)
			},
			async bind_mobile() {
				let phoneReg = /^1[1-9][0-9]\d{8}$/;
				var _this = this;
				//验证手机号码
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(_this.phoneNumber))) {
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				try {
					if (_this.phoneNumber == '') {
						throw '请填写手机号';
					}
					if (!phoneReg.test(_this.phoneNumber)) {
						throw '手机号格式有误';
					}
				} catch (err) {
					uni.showToast({
						title: err,
						icon: "none"
					});
					return;
				}
				var secret = uni.getStorageSync('wx_code');
				// plus.nativeUI.alert("**code**" + secret);
				var params = {
					mobile: _this.phoneNumber,
					captcha: _this.code,
					type: 'wechat',
					secret: secret,
				}
				//绑定手机号码
				let data = await Api.apiCall('post', Api.index.bind_mobile, params);
				let type = 'weixin';
				if(data)
				{
					_this.logining = true;
					// 绑定手机号码成功后 模拟用户登录
					_this.getUserInfo(secret, type);
				}
			},
			async getUserInfo(code, type) {
				// 从服务器获取用户数据
				var _this = this;
				var secret_key = uni.getStorageSync('secret_key'); //获取服务器公钥
				_this.privateKey = uni.getStorageSync('privateKey');
				_this.publicKey = uni.getStorageSync('publicKey');
				var info = JSON.stringify({
					"type": type,
					"mobile": _this.phoneNumber,
					"secret": code
				});
				var encryptor = new JSEncrypt({
					default_key_size: 1024
				});
				encryptor.setPublicKey(secret_key); //创建加密对象
				var encrypt_txt = encryptor.encrypt(info); //生成加密字符串
				var params = {
					"secret_key": uni.getStorageSync('secret_key'),
					"content": encrypt_txt,
					"client_key": _this.publicKey
				}
				let data = await Api.apiCall('post', Api.index.login, params);
				if (data.code == 0) {
					var decryptor = new JSEncrypt({
						default_key_size: 1024
					});
					decryptor.setPrivateKey(_this.privateKey);
					var decrypt_txt = decryptor.decrypt(data.data.content); //解密
					decrypt_txt = JSON.parse(decrypt_txt); //json字符串转Json对像
					if (decrypt_txt.token) {
						var userInfo = {
							sid: data.sid,
							mobile: _this.phoneNumber,
							token: decrypt_txt.token
						}
						_this.login(userInfo); //保存登录缓存
						uni.switchTab({
							url: '/pages/user/user',
						});
					} else {
						_this.logining = false;
					}
				}
				else {
					uni.showToast({
						title: data.error,
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "../../static/css/login.scss";

	.form {
		width: 100%;
		.res {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100upx;
			font-size: 28upx;
			color: rgba($color: #767777, $alpha: 0.8);
		}
	}
</style>
